// 作业提交控制器
const { Submission, Homework, User, Class, sequelize } = require('../models');
const { Op } = require('sequelize');
const fileUploader = require('../utils/fileUploader');

/**
 * 作业提交控制器
 * 处理作业提交和评分相关的业务逻辑
 */
class SubmissionController {
  /**
 * 学生提交作业
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
  static async submitHomework(req, res) {
    try {
      // 支持两种命名格式：前端使用homework_id，保持与前端一致
      const homeworkId = req.body.homework_id || req.body.homeworkId;
      const content = req.body.content;
      const studentId = req.user.id;
      const isResubmit = req.body.isResubmit === 'true';

      // 验证输入
      if (!homeworkId || !content) {
        return res.status(400).json({
          success: false,
          message: '请选择作业并输入提交内容'
        });
      }

      // 检查作业是否存在
      const homework = await Homework.findByPk(homeworkId);
      if (!homework) {
        return res.status(404).json({
          success: false,
          message: '作业不存在'
        });
      }

      // 检查是否已经提交过
      const existingSubmissions = await Submission.findAll({
        where: { homeworkId, studentId }
      });

      // 处理附件路径
      let attachment = null;
      if (req.file) {
        attachment = `/uploads/${req.query.type || 'submission'}/${req.file.filename}`;
      }

      // 处理粘贴的图片数据 - 将Base64图片保存为文件
      let imagePaths = [];
      
      // 强制打印收到的数据，确保能看到调试信息
      console.log('=== 开始处理图片数据 ===');
      console.log('收到的images数据:', req.body.images);
      console.log('images数据类型:', typeof req.body.images);
      
      // 处理前端传递的图片数据
      if (req.body.images) {
        try {
          // 解析前端传来的JSON字符串
          const imageDataUrls = JSON.parse(req.body.images);
          
          if (Array.isArray(imageDataUrls) && imageDataUrls.length > 0) {
            // 批量保存图片并获取路径
            imagePaths = await fileUploader.saveMultipleImages(
              imageDataUrls,
              `submission_${studentId}_${Date.now()}`
            );
            console.log('保存的图片路径:', imagePaths);
          }
        } catch (parseError) {
          console.error('解析图片数据失败:', parseError);
          // 如果解析失败，不中断流程，只是不保存图片
        }
      }
      
      console.log('最终保存的images数据:', imagePaths);
      console.log('=== 图片数据处理完成 ===');

      // 如果是重新提交被退回的作业
      if (isResubmit) {
        // 检查是否有被退回的记录
        // 使用isRejectedRecord字段代替rejected字段，与前端保持一致
        const rejectedSubmission = existingSubmissions.find(sub => sub.isRejectedRecord === true);
        
        if (!rejectedSubmission) {
          return res.status(400).json({
            success: false,
            message: '只有被退回的作业才能重新提交'
          });
        }
        
        // 开启事务
        const transaction = await sequelize.transaction();
        
        try {
          // 删除被退回的记录
          await rejectedSubmission.destroy({ transaction });
          
          // 创建新的提交记录
          const submission = await Submission.create({
            homeworkId,
            studentId,
            content,
            attachment,
            images: imagePaths,
            submittedAt: new Date()
          }, { transaction });
          
          await transaction.commit();
          
          res.json({
            success: true,
            message: '作业重新提交成功',
            data: submission
          });
        } catch (error) {
          await transaction.rollback();
          throw error;
        }
      } else {
        // 检查是否有被退回的提交记录
        // 使用isRejectedRecord字段代替rejected字段，与前端保持一致
        const hasRejectedSubmission = existingSubmissions.some(sub => sub.isRejectedRecord === true);
        // 检查是否有未被退回的提交记录
        const hasValidSubmission = existingSubmissions.some(sub => sub.isRejectedRecord !== true);
        
        // 如果有未被退回的提交记录且没有被退回的记录，则不允许重复提交
        // 但是如果有被退回的记录，允许重新提交
        if (hasValidSubmission && !hasRejectedSubmission) {
          return res.status(400).json({
            success: false,
            message: '您已经提交过该作业，请不要重复提交'
          });
        }
        
        // 创建新的提交
        const submission = await Submission.create({
          homeworkId,
          studentId,
          content,
          attachment,
          images: imagePaths,
          submittedAt: new Date()
        });

        res.json({
          success: true,
          message: '作业提交成功',
          data: submission
        });
      }
    } catch (error) {
      console.error('提交作业失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取提交列表（教师查看）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getSubmissionList(req, res) {
    try {
      const { class_id, classId, homeworkId, homework_id, grade } = req.query;
      const finalClassId = class_id || classId;
      const finalHomeworkId = homeworkId || homework_id;

      let whereCondition = {};
      let include = [
        { model: Homework, as: 'homework', attributes: ['id', 'title'] },
        { 
          model: User, 
          as: 'student', 
          attributes: ['id', 'username', 'name'],
          where: finalClassId ? { classId: finalClassId } : {},
          include: [{
            model: Class, 
            as: 'classInfo', 
            attributes: ['id', 'className', 'grade'],
            where: grade ? { grade } : {}
          }]
        }
      ];

      // 筛选条件
      if (finalHomeworkId) {
        whereCondition.homeworkId = finalHomeworkId;
      }

      const submissions = await Submission.findAll({
        where: whereCondition,
        include,
        order: [['submittedAt', 'DESC']]
      });

      res.json({
        success: true,
        data: submissions
      });
    } catch (error) {
      console.error('获取提交列表失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取学生的提交历史
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getStudentSubmissions(req, res) {
    try {
      const studentId = req.user.id;

      const submissions = await Submission.findAll({
        where: { studentId },
        include: [
          { model: Homework, as: 'homework', attributes: ['id', 'title', 'createdAt'] },
          { model: User, as: 'grader', attributes: ['id', 'username'] }
        ],
        order: [['submittedAt', 'DESC']]
      });

      res.json({
        success: true,
        data: submissions
      });
    } catch (error) {
      console.error('获取提交历史失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 教师评分
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async gradeSubmission(req, res) {
    try {
      const { submissionId } = req.params;
      const { score, comment } = req.body;
      const teacherId = req.user.id;

      // 验证输入
      if (score === undefined || score === null) {
        return res.status(400).json({ 
          success: false, 
          message: '请输入评分'
        });
      }

      if (score < 0 || score > 5) {
        return res.status(400).json({ 
          success: false, 
          message: '评分必须在0-5分之间'
        });
      }

      // 查找提交记录
      const submission = await Submission.findByPk(submissionId);
      if (!submission) {
        return res.status(404).json({ 
          success: false, 
          message: '提交记录不存在'
        });
      }

      // 更新评分
      await submission.update({
        score,
        comment,
        gradedBy: teacherId,
        gradedAt: new Date()
      });

      res.json({
        success: true,
        message: '评分成功',
        data: submission
      });
    } catch (error) {
      console.error('评分失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 教师退回作业
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async rejectSubmission(req, res) {
    try {
      const { submissionId } = req.params;
      const { comment } = req.body;
      const teacherId = req.user.id;

      // 查找提交记录
      const submission = await Submission.findByPk(submissionId);
      if (!submission) {
        return res.status(404).json({ 
          success: false, 
          message: '提交记录不存在' 
        });
      }

      // 退回作业：设置评分为0分，保留记录
      await submission.update({
        score: 0, // 退回时评分为0
        comment: comment || '作业未完成相应任务，需要重新提交',
        gradedBy: teacherId,
        gradedAt: new Date(),
        rejected: true, // 标记为已退回
        isRejectedRecord: true // 明确标识为退回作业记录
      });

      res.json({
        success: true,
        message: '作业退回成功',
        data: submission
      });
    } catch (error) {
      console.error('退回作业失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取年级排名前10
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getGradeRanking(req, res) {
    try {
      const { grade } = req.query;

      // 获取年级总分排名
      const rankings = await sequelize.query(`
        SELECT 
          u.id, 
          u.name, 
          c.className, 
          c.grade, 
          SUM(s.score) as total_score
        FROM 
          users u
        JOIN 
          classes c ON u.classId = c.id
        JOIN 
          submissions s ON u.id = s.studentId
        WHERE 
          u.role = 'student' AND 
          c.grade = :grade AND
          s.score IS NOT NULL
        GROUP BY 
          u.id
        ORDER BY 
          total_score DESC
        LIMIT 10
      `, {
        replacements: { grade },
        type: sequelize.QueryTypes.SELECT
      });

      res.json({
        success: true,
        data: rankings
      });
    } catch (error) {
      console.error('获取年级排名失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取班级排名
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getClassRanking(req, res) {
    try {
      const { classId } = req.params;

      // 获取班级总分排名
      const rankings = await sequelize.query(`
        SELECT 
          u.id, 
          u.name,
          u.username, 
          SUM(s.score) as total_score
        FROM 
          users u
        JOIN 
          submissions s ON u.id = s.studentId
        WHERE 
          u.role = 'student' AND 
          u.classId = :classId AND
          s.score IS NOT NULL
        GROUP BY 
          u.id
        ORDER BY 
          total_score DESC
        LIMIT 20
      `, {
        replacements: { classId },
        type: sequelize.QueryTypes.SELECT
      });

      res.json({
        success: true,
        data: rankings
      });
    } catch (error) {
      console.error('获取班级排名失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }
}

module.exports = SubmissionController;